package com.kly.user.task.service;

import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Maps;
import com.kly.user.db.dao.UserChatterMappingDao;
import com.kly.user.db.dao.UserTaskDetailDao;
import com.kly.user.db.entity.UserChatterMappingEntity;
import com.kly.user.db.entity.UserTaskJobEntity;
import com.kly.user.msgClient.MsgAPI;
import com.kly.user.task.ExecuteHandler;
import com.kly.user.task.ExecuteResult;
import com.kly.user.task.enums.TaskStatusEnum;
import com.kly.user.task.enums.TaskTypeEnum;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * push 系统消息(暂不使用）
 */
@Service("pushNoticeImpl")
public class NoticePushImpl implements ExecuteHandler {
    private static Log logger = LogFactory.getLog("taskFileLog");

    @Resource
    MsgAPI msgAPI;
    @Resource
    UserChatterMappingDao userChatterMappingDao;
    @Resource
    UserTaskDetailDao userTaskDetailDao;

    @Override
    public TaskTypeEnum getType() {
        return TaskTypeEnum.NOTICE_PUSH;
    }

    @Override
    public <T> ExecuteResult doExecute(T t) throws Exception {

        UserTaskJobEntity entity = (UserTaskJobEntity) t;
        logger.info("Notice push job starting, job detail:{}", JSONObject.toJSONString(entity));

        final List<UserChatterMappingEntity> chatters = queryChatters();
        if (CollectionUtils.isEmpty(chatters)) {
            logger.info("Notice push job starting, job detail: NO_CHATTER_EXISTS");
            return ExecuteResult.builder().jobId(entity.getId()).resultMsg("success").resultCode(TaskStatusEnum.SUCCESS.getCode()).taskType(TaskTypeEnum.NOTICE_PUSH.getCode()).build();
        }

        final List<String> chatterUserCodes = chatters.parallelStream().map(UserChatterMappingEntity::getChatterUserCode).distinct().collect(Collectors.toList());
        chatterUserCodes.forEach(userCode -> {
            msgAPI.postNoticeRequest(userCode);

        });

        logger.info("Notice push job end");
        return ExecuteResult.builder().jobId(entity.getId()).resultMsg("success").resultCode(TaskStatusEnum.SUCCESS.getCode()).taskType(TaskTypeEnum.NOTICE_PUSH.getCode()).build();
    }

    private List<UserChatterMappingEntity> queryChatters() {
        Map<String, Object> params = Maps.newHashMap();
        params.put("status", 1);
        return userChatterMappingDao.selectByParams(params);
    }

}
